package cn.edu.swu.mhans.web.controller.admin;

import cn.edu.swu.mhans.user.model.SystemRole;
import cn.edu.swu.mhans.user.model.SystemUser;
import cn.edu.swu.mhans.user.service.RoleService;
import cn.edu.swu.mhans.user.service.UserService;
import cn.edu.swu.mhans.web.common.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2018/4/24
 */
@Controller
@RequestMapping("/admin/user")
public class AdminUserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping(value = {"/", "/index"})
    public ModelAndView userList() {
        ModelAndView mav = new ModelAndView();
        List<SystemUser> userList = userService.findAll();
        mav.addObject("userList", userList);
        mav.setViewName("/admin/user/index");
        return mav;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String changeUserRole(SystemUser systemUser, Long[] roleIds) {
        List<SystemRole> roleList = roleService.findAllByIdIn(Arrays.asList(roleIds));
        systemUser.setRoles(roleList);
        userService.update(systemUser);
        return "redirect:/admin/user/index";
    }

    @RequestMapping("/delete")
    public String deleteUser(Long userId) {
        userService.delete(userId);
        return redirectToIndex();
    }

    @RequestMapping("/detail")
    public ModelAndView userDetail(Long userId) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", userService.findOne(userId));
        mav.addObject("roleList", roleService.findAll());
        mav.setViewName("/admin/user/detail");
        return mav;
    }

    private String redirectToIndex() {
        return "redirect:/admin/user/";
    }

}
